<template>
	<view class="container">
		<view class="course-banner">
			<video id="myVideo" :src="videoUrl" autoplay="true" :enable-progress-gesture="false" @play="onPlay" @pause="onPause" @timeupdate="bindtimeupdate" controls ></video>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				baseURL: getApp().globalData.baseUrl,
				videoUrl: '',
				videoContext: null,
				timer: null,
				totalPlayTime: 0, 
				lastUpdateTime: 0,  
				isPlaying: false,
				hasReported15min: false,
				vId: 0,
				historyTime: 0,
			}
		},
		onLoad(options) {
			this.videoUrl = options.urls ?? ''
			console.log(options)
			this.vId = options.vid ?? 0
			this.videoContext = uni.createVideoContext('myVideo')
		},
		onShow(){ },
		onHide() {
			console.log('11111111111')
			this.clearTimer()
		},
		methods: {
			// 视频状态监听
			onPlay() {
				this.isPlaying = true
				this.lastUpdateTime = Date.now()
				this.startTimer()
			},
			// 监听播放进度
			bindtimeupdate(e) {
				var currentTime = e.detail.currentTime;
				if (currentTime - this.historyTime > 2) {
					uni.showToast({
						title: '不能快进哦',
						icon: 'none',
					});
					let videoContext = uni.createVideoContext('myVideo');
					videoContext.seek(this.historyTime);
				}
				this.historyTime = currentTime;
			},
			    
			onPause() {
				this.isPlaying = false
				this.clearTimer()
			},
			    
			// 定时器管理
			startTimer() {
				this.timer = setInterval(() => {
					if (this.isPlaying) {
						const currentTime = Date.now()
						const delta = (currentTime - this.lastUpdateTime) / 1000
						this.totalPlayTime += delta
						// 常规10秒上报
						if (Math.floor(this.totalPlayTime) % 10 === 0) {
							this.recordUp(false)
						}
						// 15分钟上报并暂停
						if (this.totalPlayTime >= 900 && !this.hasReported15min) {
							this.hasReported15min = true
							this.videoContext.pause()
							this.recordUp(true)
						}
						this.lastUpdateTime = currentTime
					}
				}, 1000)
			},
			    
			clearTimer() {
				clearInterval(this.timer)
				this.timer = null
			},
			    
			// 上报方法
			recordUp(isFinal) {
				const reportData = {
					appid:uni.getStorageSync('appid'),
					v_id: this.vId,
					duration: Math.floor(this.totalPlayTime),
					is_completed: isFinal,
					timestamp: Date.now()
				}
			  
				uni.request({
					url: this.baseURL + '/api/user/recordPut',
					method: 'POST',
					data: reportData,
					success: () => {
						console.log('播放记录上报成功', reportData)
					},
					fail: (err) => {
						console.error('上报失败:', err)
					}
				})
				  // 如果是最终上报则重置计时
				if (isFinal) {
					this.totalPlayTime = 0
					this.hasReported15min = false
				}
			},
			onUnload() {
				if (this.totalPlayTime > 0) {
				  this.recordUp(false)
				}
				this.clearTimer()
			}
		}
	}
</script>

<style>
	.container {background-color: #f8f8f8;height: 100vh;background: #FCD752;}
	.course-banner {width: 100%;display: block;padding-top: 50%;}
	.course-banner video{width: 100%;}
</style>